package com.daxidi.cn.config;

import com.daxidi.cn.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author JiaLin
 * create 2020-11-07
 */
@Slf4j
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        String requestURI = request.getRequestURI().replaceAll("/+", "/");
        //log.info("requestURI:{}", requestURI);

        Claims claim = JWTUtils.getClaim(token);
        if (!ObjectUtils.isEmpty(claim)){
            String str = JWTUtils.getOpenId(token);
            //log.info("登录成功！手机号是：" + str);
        }
        if (ObjectUtils.isEmpty(claim)){
            throw new RuntimeException("no_login");
        }

        return true;
    }
}
